package model;

import java.util.ArrayList;
import java.util.Iterator;

public class Territoire {

	
	
	private static int maxX;
	private static int maxY;
	private static int cellSize;
	
	private static ArrayList<Cellule> cellsList = new ArrayList<Cellule>();
	private static ArrayList<Cellule> busyCellsList = new ArrayList<Cellule>();
	
	private static Territoire instance= new Territoire();	
	private Territoire(){
	}
	public static Territoire getInstance(){
		return instance;
	}
	
	public static void setTerritoire (int _maxX, int _maxY, int _cellSize){
		maxX = _maxX;
		maxY = _maxY;
		cellSize = _cellSize;
		for(int i=0;i< maxX;i++){
			for(int j=0;j< maxY;j++){
				cellsList.add(new Cellule(i,j,cellSize));
			}
		}
		Cellule up,down,left,right;
		int indicelist = 0;
		for(int i=0;i< maxX;i++){
			for(int j=0;j< maxY;j++){
				up = i==0 ? null : cellsList.get(indicelist-maxX);
				down = i == maxX-1 ? null : cellsList.get(indicelist+maxX);
				right = j == maxY-1 ? null : cellsList.get(indicelist+1);
				left =  j == 0 ? null : cellsList.get(indicelist-1);
				cellsList.get(indicelist).setNeightbour(up, right, left, down);
				indicelist++;
			}
		}
	}
	public static int getMaxX(){
		return maxX;
	}
	
	public static int getMaxY(){
		return maxY;
	}
	
	public static Cellule getCells(int i,int j){
		for(Cellule c:cellsList){
			if(c.getX()==i && c.getY()==j) return c;
		}
		return null;
	}
	
	public static boolean cellBusy(int i,int j){
		for(Cellule c:busyCellsList){
			if(c.getX()==i && c.getY()==j && c.isBusy()) return true;
		}
		return false;
	}
		
	public static void updateCellStatut(Cellule cell){
		if(cell.isBusy()){
			if(!busyCellsList.contains(cell)){
				busyCellsList.add(cell);
			}
		}else{
			if(busyCellsList.contains(cell)){
				busyCellsList.remove(cell);
			}
		}
	}	
	
	public static void updateAllCell(){		
		ArrayList<Cellule> cloneList = (ArrayList<Cellule>) cellsList.clone();
		Iterator<Cellule> it = cloneList.iterator();
		while(it.hasNext()){
			updateCellStatut(it.next());		
		}
	}
	
}
